package com.metel.mservice.common.secure;

import org.apache.commons.dbcp.BasicDataSource;

import com.metel.mservice.common.encrypt.AES128ECBUtil;

/**
 * DataSource setup by decryption of secured MySQL username and password
 * @author hyungjin.ahn
 *
 */
public class SecureJdbcDataSource extends BasicDataSource {

	@Override
	public void setUsername(String username) {
		byte[] byteArrayDecodedValue = hexToByteArray(username);
		if(byteArrayDecodedValue == null) return;
		byte[] decryptedUsername = AES128ECBUtil.decrypt(AES128ECBUtil.privateDBEncKey, byteArrayDecodedValue);
		if(decryptedUsername == null) return;
		
		super.setUsername(new String(decryptedUsername));
	}
	
	@Override
	public void setPassword(String password) {
		byte[] byteArrayDecodedValue = hexToByteArray(password);
		if(byteArrayDecodedValue == null) return;
		byte[] decryptedPassword = AES128ECBUtil.decrypt(AES128ECBUtil.privateDBEncKey, byteArrayDecodedValue);
		if(decryptedPassword == null) return;
		
		super.setPassword(new String(decryptedPassword));
	}
	
	/**
	 * byte[] to Hex
	 * @param hexEncodingValue
	 * @return
	 */
	private byte[] hexToByteArray(String hexEncodingValue) {
		
		if (hexEncodingValue == null || hexEncodingValue.length() == 0) {
			return null;
		}
		
		byte[] decryptedByteArray = new byte[hexEncodingValue.length() / 2];
		for (int i = 0;  i < decryptedByteArray.length;  i++) {
			decryptedByteArray[i] = (byte) Integer.parseInt(hexEncodingValue.substring(2 * i, 2 * i + 2), 16);
		}
		
		return decryptedByteArray;
	}
}
